package com.tengju.support.infrastructure.repository.resource.convert;

import com.fasterxml.jackson.core.type.TypeReference;
import com.tengju.support.domain.model.resource.*;
import com.tengju.support.domain.shared.IdObject;
import com.tengju.support.domain.shared.JsonUtil;
import com.tengju.support.infrastructure.persistence.mybatis.dataobject.AppBannerInfoDO;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class ResourceConvert {

    public static Resource convertToModel(AppBannerInfoDO appBannerInfoDO) {
        if (null == appBannerInfoDO) {
            return null;
        }

        List<ResourceOrientation> resourceOrientations = new ArrayList<>();
        if (!StringUtils.isEmpty(appBannerInfoDO.getUserOrientation())) {
            resourceOrientations = JsonUtil.toList(appBannerInfoDO.getUserOrientation(), new TypeReference<>() {
            });
        }

        return new Resource(
                new ResourceId(appBannerInfoDO.getBannerId()),
                JumpAction.fromVal(appBannerInfoDO.getJumpAction()),
                appBannerInfoDO.getImgUrl(),
                appBannerInfoDO.getTitle(),
                appBannerInfoDO.getJumpUrl(),
                appBannerInfoDO.getCreateBy(),
                Position.fromVal(appBannerInfoDO.getPosition()),
                appBannerInfoDO.getBeginTime(),
                appBannerInfoDO.getEndTime(),
                resourceOrientations,
                appBannerInfoDO.getPriority(),
                appBannerInfoDO.getUpdateBy(),
                appBannerInfoDO.getCreateTime()
        );
    }

    public static AppBannerInfoDO convertToDO(Resource resource) {

        return new AppBannerInfoDO(
                Optional.ofNullable(resource.getResourceId()).map(IdObject::getValue).orElse(null),
                resource.getAction().getVal(),
                resource.getImgUrl(),resource.getTitle(),
                resource.getJumpUrl(),
                resource.getCreateBy(),
                null,null,null,
                resource.getPosition().getVal(),
                resource.getBeginTime(),
                resource.getEndTime(),
                Optional.ofNullable(resource.getUserOrientation())
                        .map(JsonUtil::toJSONString).orElse(JsonUtil.toJSONString(new ArrayList<>())),
                resource.getPriority(),resource.getUpdateBy()
        );
    }
}
